package com.xy6.jvm.fork.test;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * 任务拥有返回值示例：
 * 随机生成一个数组，每个元素均是0-999之间的整数，统计该数组中每个数字出现1的次数的和。
 * 
 * @author frank
 * @since 2018-01-01
 */
public class StatNumTask extends RecursiveTask<Integer> {

	private static final long serialVersionUID = 1894872981986954674L;
	
	/**
	 * 一组数字
	 */
	private int[] array;
	private int begin;
	private int end;
	
	public StatNumTask(int[] array, int begin, int end){
		this.array = array;
		this.begin = begin;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		int result = 0;
		if(end - begin > 1){
			int middle = (begin + end) >>> 1;
			StatNumTask t1 = new StatNumTask(array, begin, middle);
			StatNumTask t2 = new StatNumTask(array, middle + 1, end);
			invokeAll(t1, t2);
			try{
				result = t1.get() + t2.get();
			} catch(InterruptedException | ExecutionException e){
				e.printStackTrace();
			}
		} else if(end - begin == 1) {
			result = count(array[begin]) + count(array[end]);
		} else {
			result = count(array[begin]);
		}
		return result;
	}

	/**
	 * 统计一个整数出现多少个1
	 * 
	 * @param n
	 * @return
	 */
	private int count(int n){
		int count = 0;
		while(n > 0){
			if(n % 10 == 1){
				count ++;
			}
			n = n / 10;
		}
		return count;
	}
	

	public final static ForkJoinPool mainPool = new ForkJoinPool();

	public static void main(String[] args) {
		int n = 10;
		int[] a = new int[n];
		Random r = new Random();
		for (int i = 0; i < n; i++) {
			a[i] = r.nextInt(20);
		}
		System.out.println(Arrays.toString(a));
		StatNumTask task = new StatNumTask(a, 0, n - 1);
		int result = mainPool.invoke(task);
		System.out.println(result);
	}
	
}
